<template>
  <el-dialog
    :title="title"
    v-model="visible"
    width="500px"
    append-to-body
    destroy-on-close
	 :close-on-click-modal="false"
	@close="handleCloseDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="类别名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入类别名称" />
      </el-form-item>
      <el-form-item label="上级类别" prop="parentId">
        <el-tree-select
          v-model="formData.parentId" 
          placeholder="请选择上级类别"
          clearable
          style="width: 100%"
          :data="categoryOptions"
          :props="{
            value: 'id',
            label: 'name',
            children: 'children'
          }"
          check-strictly
          :render-after-expand="false"
          :filter-node-method="filterNode"
        />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="handleCloseDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
import type { BlueprintNodeCategoryForm, BlueprintNodeCategoryVO } from '@/api/biz/blueprintnode';
import BlueprintNodeAPI from '@/api/biz/blueprintnode';
import {recurOptions} from "@/utils/TreeUtil";

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  title: {
    type: String,
    required: true
  },
  category: {
    type: Object as () => BlueprintNodeCategoryVO,
    required: true
  }
});

const emit = defineEmits(['update:modelValue', 'success']);
const visible = ref(false);
const formRef = ref();
const formData = reactive<BlueprintNodeCategoryForm>({
  id: '',
  name: '',
  parentId: '-1',
  sort: 0
});

const rules = {
  name: [{ required: true, message: '请输入类别名称', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
};

const categoryOptions = ref<any[]>([]);

const filterNode = (value: string, data: BlueprintNodeCategoryVO) => {
  if (!value) return true;
  return data.name.toLowerCase().includes(value.toLowerCase());
};

const getCategoryOptions = async () => {
  try {
    const data = await BlueprintNodeAPI.getCategoryPage({});
    categoryOptions.value = [{
      id: '-1',
      name: '顶级类别',
      children: recurOptions(data, '-1')
    }];
  } catch (error) {
    console.error('获取类别选项失败:', error);
  }
};

onMounted(() => {
  getCategoryOptions();
});

watch(() => props.modelValue, (val) => {
  visible.value = val;
  getCategoryOptions();
});

watch(() => visible.value, (val) => {
  emit('update:modelValue', val);
});

watch(
  () => props.category,
  (val) => {
    Object.assign(formData, val);
    if (categoryOptions.value.length > 0) {
      categoryOptions.value = [{
        id: '-1',
        name: '顶级类别',
        children: disableSelfAndChildren(categoryOptions.value[0].children || [])
      }];
    }
  },
  { deep: true }
);

const submitForm = async () => {
  await formRef.value?.validate();
  
  await BlueprintNodeAPI.saveCategory(formData);
  ElMessage.success('保存成功');
  handleCloseDialog();
  emit('success');
};

function resetForm() {
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
  formData.id = "";
  formData.name = "";
  formData.parentId = "-1";
  formData.sort = 0;
}

function handleCloseDialog() {
  visible.value = false;
  resetForm();
}

const disableSelfAndChildren = (data: any[]) => {
  return data.map(item => {
    const newItem = { ...item };
    if (newItem.id === formData.id) {
      newItem.disabled = true;
    }
    if (newItem.children) {
      newItem.children = disableSelfAndChildren(newItem.children);
    }
    return newItem;
  });
};
</script> 